package dao

import (
	"fmt"
	"order_srv/basic/config"
	"order_srv/handler/models"
	"time"
)

// GetOperator 获取操作员信息
func GetOperator(operatorID string) (*models.Operator, error) {
	var operator models.Operator
	err := config.DB.Where("operator_id = ?", operatorID).First(&operator).Error
	if err != nil {
		return nil, fmt.Errorf("获取操作员信息失败: %v", err)
	}
	return &operator, nil
}

// GetAvailableOperators 获取可用操作员列表
func GetAvailableOperators(operatorType string) ([]*models.Operator, error) {
	var operators []*models.Operator
	query := config.DB.Where("status = ?", 1) // 正常状态

	if operatorType != "" {
		query = query.Where("operator_type = ?", operatorType)
	}

	err := query.Order("current_order_count ASC").Find(&operators).Error
	if err != nil {
		return nil, fmt.Errorf("获取可用操作员列表失败: %v", err)
	}

	return operators, nil
}

// UpdateOperatorOrderCount 更新操作员接单数量
func UpdateOperatorOrderCount(operatorID string, count int32) error {
	return config.DB.Model(&models.Operator{}).
		Where("operator_id = ?", operatorID).
		Update("current_order_count", count).Error
}

// UpdateOperatorActivity 更新操作员活跃时间
func UpdateOperatorActivity(operatorID string) error {
	now := time.Now()
	return config.DB.Model(&models.Operator{}).
		Where("operator_id = ?", operatorID).
		Update("last_active_time", now).Error
}

// GetOperatorStats 获取操作员统计信息
func GetOperatorStats(operatorID string) (map[string]interface{}, error) {
	var stats map[string]interface{} = make(map[string]interface{})

	// 获取操作员基本信息
	operator, err := GetOperator(operatorID)
	if err != nil {
		return nil, err
	}

	stats["operator_id"] = operator.OperatorID
	stats["operator_name"] = operator.OperatorName
	stats["operator_type"] = operator.OperatorType
	stats["current_order_count"] = operator.CurrentOrderCount
	stats["max_order_count"] = operator.MaxOrderCount
	stats["acceptance_rate"] = operator.AcceptanceRate
	stats["average_response_time"] = operator.AverageResponseTime
	stats["last_active_time"] = operator.LastActiveTime

	// 计算负载率
	var loadRate float64
	if operator.MaxOrderCount > 0 {
		loadRate = float64(operator.CurrentOrderCount) / float64(operator.MaxOrderCount) * 100
	}
	stats["load_rate"] = loadRate

	// 获取今日接单数
	today := time.Now().Format("2006-01-02")
	var todayOrders int64
	err = config.DB.Model(&models.OrderAcceptance{}).
		Where("operator_id = ? AND DATE(created_at) = ? AND action = ?", operatorID, today, "accept").
		Count(&todayOrders).Error
	if err != nil {
		todayOrders = 0
	}
	stats["today_orders"] = todayOrders

	// 获取本周接单数
	weekStart := time.Now().AddDate(0, 0, -int(time.Now().Weekday())).Format("2006-01-02")
	var weekOrders int64
	err = config.DB.Model(&models.OrderAcceptance{}).
		Where("operator_id = ? AND DATE(created_at) >= ? AND action = ?", operatorID, weekStart, "accept").
		Count(&weekOrders).Error
	if err != nil {
		weekOrders = 0
	}
	stats["week_orders"] = weekOrders

	// 获取本月接单数
	monthStart := time.Now().AddDate(0, 0, -time.Now().Day()+1).Format("2006-01-02")
	var monthOrders int64
	err = config.DB.Model(&models.OrderAcceptance{}).
		Where("operator_id = ? AND DATE(created_at) >= ? AND action = ?", operatorID, monthStart, "accept").
		Count(&monthOrders).Error
	if err != nil {
		monthOrders = 0
	}
	stats["month_orders"] = monthOrders

	return stats, nil
}

// GetTopOperators 获取热门操作员
func GetTopOperators(limit int, operatorType string) ([]*models.Operator, error) {
	var operators []*models.Operator
	query := config.DB.Where("status = ?", 1)

	if operatorType != "" {
		query = query.Where("operator_type = ?", operatorType)
	}

	err := query.Order("acceptance_rate DESC, current_order_count DESC").
		Limit(limit).
		Find(&operators).Error
	if err != nil {
		return nil, fmt.Errorf("获取热门操作员失败: %v", err)
	}

	return operators, nil
}

// UpdateOperatorAcceptanceRate 更新操作员接单率
func UpdateOperatorAcceptanceRate(operatorID string) error {
	// 计算接单率
	var totalOrders int64
	var acceptedOrders int64

	// 获取总订单数
	err := config.DB.Model(&models.OrderAcceptance{}).
		Where("operator_id = ?", operatorID).
		Count(&totalOrders).Error
	if err != nil {
		return fmt.Errorf("获取总订单数失败: %v", err)
	}

	// 获取已接单数
	err = config.DB.Model(&models.OrderAcceptance{}).
		Where("operator_id = ? AND action = ? AND status = ?", operatorID, "accept", 1).
		Count(&acceptedOrders).Error
	if err != nil {
		return fmt.Errorf("获取已接单数失败: %v", err)
	}

	// 计算接单率
	var acceptanceRate float64
	if totalOrders > 0 {
		acceptanceRate = float64(acceptedOrders) / float64(totalOrders) * 100
	}

	// 更新接单率
	return config.DB.Model(&models.Operator{}).
		Where("operator_id = ?", operatorID).
		Update("acceptance_rate", acceptanceRate).Error
}

// UpdateOperatorResponseTime 更新操作员平均响应时间
func UpdateOperatorResponseTime(operatorID string) error {
	// 计算平均响应时间
	var avgResponseTime int64
	err := config.DB.Model(&models.OrderAcceptance{}).
		Where("operator_id = ? AND action = ? AND status = ?", operatorID, "accept", 1).
		Select("AVG(response_time)").
		Scan(&avgResponseTime).Error
	if err != nil {
		avgResponseTime = 0
	}

	// 更新平均响应时间
	return config.DB.Model(&models.Operator{}).
		Where("operator_id = ?", operatorID).
		Update("average_response_time", avgResponseTime).Error
}

// GetOperatorList 获取操作员列表
func GetOperatorList(page, pageSize int, operatorType string, status int8) ([]*models.Operator, int64, error) {
	var operators []*models.Operator
	var total int64

	query := config.DB.Model(&models.Operator{})

	if operatorType != "" {
		query = query.Where("operator_type = ?", operatorType)
	}
	if status >= 0 {
		query = query.Where("status = ?", status)
	}

	// 计算总数
	err := query.Count(&total).Error
	if err != nil {
		return nil, 0, fmt.Errorf("获取操作员总数失败: %v", err)
	}

	// 分页查询
	offset := (page - 1) * pageSize
	err = query.Order("created_at DESC").
		Offset(offset).
		Limit(pageSize).
		Find(&operators).Error
	if err != nil {
		return nil, 0, fmt.Errorf("获取操作员列表失败: %v", err)
	}

	return operators, total, nil
}
